package cn.com.wantools.service.provider;

import cn.com.wantools.model.unitconvert.UcConvertType;
import cn.com.wantools.model.unitconvert.UcConvertTypeDto;
import cn.com.wantools.model.unitconvert.UcGroup;
import cn.com.wantools.model.unitconvert.UcGroupDto;
import cn.com.wantools.service.UcConvertTypeService;
import cn.com.wantools.service.UcGroupService;
import cn.com.wantools.service.UcIndexService;
import com.jfinal.aop.Inject;
import io.jboot.aop.annotation.Bean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Bean
public class UcIndexServiceProvider implements UcIndexService {

    private static int MAX_SIZE_PER_LINE = 4;

    @Inject
    private UcGroupService ucGroupService;

    @Inject
    private UcConvertTypeService ucConvertTypeService;

    @Override
    public List<UcGroupDto> loadIndexConfigService() {
        List<UcGroup> ucGroupList = ucGroupService.loadUcGroup();
        List<UcConvertType> ucConvertTypeList = ucConvertTypeService.queryAllConvertType();
        List<UcGroupDto> ucGroupDtoList = new ArrayList<>();
        for (UcGroup ucGroup : ucGroupList) {
            UcGroupDto ucGroupDto = new UcGroupDto();
            ucGroupDto.setGroupTitle(ucGroup.getGroupTitle());
            ucGroupDto.setGroupName(ucGroup.getGroupName());
            ucGroupDto.setId(ucGroup.getId());
            List<UcConvertType> tmpUcConvertTypeList = ucConvertTypeList.stream().filter(x -> ucGroup.getGroupName().equals(x.getGroupName())).collect(Collectors.toList());
            List<UcConvertTypeDto> ucConvertTypeDtoList = new ArrayList<>();
            for (int i = 0; i < tmpUcConvertTypeList.size(); i++) {
                UcConvertTypeDto ucConvertTypeDto = new UcConvertTypeDto();
                ucConvertTypeDto.setId(tmpUcConvertTypeList.get(i).getId());
                ucConvertTypeDto.setOrderNo(i);
                ucConvertTypeDto.setConvertType(tmpUcConvertTypeList.get(i).getConvertType());
                ucConvertTypeDto.setConvertTitle(tmpUcConvertTypeList.get(i).getConvertTitle());
                ucConvertTypeDto.setRemark(tmpUcConvertTypeList.get(i).getRemark());
                ucConvertTypeDto.setOrders(tmpUcConvertTypeList.get(i).getOrders());
                ucConvertTypeDto.setGroupName(tmpUcConvertTypeList.get(i).getGroupName());
                ucConvertTypeDtoList.add(ucConvertTypeDto);
            }
            Map<Integer, List<UcConvertTypeDto>> mapConvertTypeList = ucConvertTypeDtoList
                    .stream()
                    .collect(Collectors.groupingBy(x -> (int)(x.getOrderNo() / MAX_SIZE_PER_LINE)));
            List<List<UcConvertTypeDto>> list = mapConvertTypeList.entrySet().stream().sorted((x,y) -> x.getKey().compareTo(y.getKey())).map(x -> x.getValue()).collect(Collectors.toList());
            ucGroupDto.setUcConvertTypeDtoList(list);
            ucGroupDtoList.add(ucGroupDto);
        }
        return ucGroupDtoList;
    }
}
